package com.ncu.week5_listview_l9;

import android.Manifest;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import com.example.week5.R;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<ImageInfo> imgList = new ArrayList<ImageInfo>();
    private ImageListAdapter imageAdapter;
    private ListView mListView;
    private String ImageName;
    private int currentSel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1
                );
            }
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SET_WALLPAPER) == PackageManager.PERMISSION_DENIED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(
                        new String[]{Manifest.permission.SET_WALLPAPER}, 1
                );
            }
        }
        loadImageList();
        imageAdapter = new ImageListAdapter(MainActivity.this, imgList);
        mListView = (ListView) findViewById(R.id.image_list);
        mListView.setAdapter(imageAdapter);
        //上下文菜单
        registerForContextMenu(mListView);
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                ImageName = (String) imageAdapter.getItem(position);
                currentSel = position;
                mListView.showContextMenu();
                return true;
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentSel = position;
                String imgPath = imgList.get(position).getFile_path();
                if (imgPath.length() > 0) {
                    Intent intent = new Intent();
                    Bundle bl = new Bundle();
                    bl.putInt("pos", position);
                    bl.putSerializable("image_list", (Serializable) imgList);
                    intent.putExtras(bl);
                    intent.setClass(MainActivity.this, ViewActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void loadImageList() {
        String internalSdcard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
        File dirctory = new File(internalSdcard);
        File[] files = dirctory.listFiles();
        if(files!=null){
            if (files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    Uri selevtedUri = Uri.fromFile(files[i]);
                    String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selevtedUri.toString());
                    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
                    if (mimeType == "image/jpeg" || mimeType == "image/png" || mimeType == "image/bmp") {
                        ImageInfo info = new ImageInfo();
                        info.setFile_name(files[i].getName());
                        info.setFile_path(files[i].getPath());
                        Date lastModified = new Date(files[i].lastModified());
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
                        info.setFile_date(formatter.format(lastModified));
                        imgList.add(info);
                    }
                }
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(0, 0, 0, R.string.menu_wall);
        menu.add(0, 1, 1, R.string.menu_detail);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                Bitmap bm = BitmapFactory.decodeFile(imgList.get(currentSel).getFile_path());
                try {
                    //setWallpaper(bm);
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
                    wallpaperManager.setBitmap(bm);
                    Toast.makeText(MainActivity.this, "设置壁纸成功！", Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "设置壁纸失败！", Toast.LENGTH_LONG).show();
                }
                break;
            case 1:
                StringBuilder msgBuilder = new StringBuilder();
                msgBuilder.append("文件名：\n" + imgList.get(currentSel).getFile_name() + "\n");
                msgBuilder.append("修改日期：\n" + imgList.get(currentSel).getFile_date() + "\n");
                msgBuilder.append("文件路径：\n" + imgList.get(currentSel).getFile_path() + "\n");
                DetailDialog detail = new DetailDialog(this, msgBuilder.toString());
                detail.show();
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    //设置选项菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        boolean reValue = super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_item,menu);
        return reValue;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==R.id.item_about){
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("ImageViewer  V1.0.0\n");
            stringBuilder.append("作者：徐梓涵\n");
            stringBuilder.append("(c) 2020 Ncu 软件学院");
            DetailDialog detailDialog = new DetailDialog(this,stringBuilder.toString());
            detailDialog.show();
        }
        if(item.getItemId()==R.id.item_exit){
            String titile = "提示";
            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle(R.string.str_warning)
                    .setMessage("是否确定退出")
                    .setPositiveButton(R.string.btn_comfirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();//退出
                        }
                    })
                    .setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                           //啥也不干
                        }
                    }).create().show();
        }
        return  super.onOptionsItemSelected(item);
    }
}
